package luz.javaproxy.config;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import luz.javaproxy.plugin.PluginMgr;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.StreamException;

public class ConfigMgr {
	private static XStream xstream;
	private static final String config="config.xml";
	private static String configFile;
	private static final Log log = LogFactory.getLog(ConfigMgr.class);
	private ProxyConfig loadedConfig;
	private PluginMgr pMgr;
	
	public ConfigMgr(){
		configFile=getJarPath()+config;
		xstream = new XStream();
		xstream.processAnnotations(ProxyConfig.class);
		xstream.processAnnotations(PluginConfig.class);
	}
	
	public void setPluginMgr(PluginMgr pMgr){
		this.pMgr=pMgr;
	}

	public String getJarPath(){
		String path="/";
        try {
			path=this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
			path=path.replaceFirst("[^/]+\\.jar$", "");
		} catch (URISyntaxException e) {
			log.info("Unable to get Jar path. Using current dir.");
		}
		return path;
	}
	
	public void loadConfig(){
		try {
			log.info("Config loading: "+configFile);
			FileInputStream fis = new FileInputStream(configFile);
			loadedConfig=(ProxyConfig)xstream.fromXML(fis);
			log.info("Config loaded");
			fis.close();
		} catch (FileNotFoundException e) {
			log.error("Config file not found: "+configFile, e);
			loadedConfig=new ProxyConfig();
		} catch (IOException e) {
			log.error("Config file error: "+configFile, e);
			loadedConfig=new ProxyConfig();
		} catch (StreamException e){
			log.error("Config file error: "+configFile, e);
			loadedConfig=new ProxyConfig();
		}

	}
	
	public void saveConfig(){
		if (loadedConfig==null)
			loadedConfig=new ProxyConfig();

		
		//PluginConfig
		if (this.pMgr!=null){
			for (PluginConfig config : pMgr.getPluginConfigs()) {
				loadedConfig.setPluginConfig(config);
			}
		}
		
		try {
			FileOutputStream fos = new FileOutputStream(configFile);
			xstream.toXML(loadedConfig, fos);
			fos.close();
		} catch (FileNotFoundException e) {
			log.error("Config file not found: "+configFile, e);
		} catch (IOException e) {
			log.error("Config file error: "+configFile, e);
		}
		log.info("Config saved");
	}
	

	
	public ProxyConfig getProxyConfig(){
		return loadedConfig;
	}
	
	public PluginConfig getPluginConfig(String name){
		return loadedConfig.getPluginConfig(name);

	}

	
	
	
}
